trigger EventSyncForPClass on ConsumerEducation__c (after insert,before delete,after update){
boolean b=false;
if(system.trigger.isupdate){
for(ConsumerEducation__c t:trigger.new){
    if(trigger.oldmap.get(t.id).date__c!=t.date__c){
        b=true;
    }
}
}


   List<Event> eventl=new List<Event>();
   list<id> idl=new list<id>();
   list<event> eventupd=new list<event>();
   list<event> eventins=new list<event>();
    list<datetime> cpdate=new list<datetime>();
   datetime newdate;
    datetime olddate;
   list<recordtype> allrt=[select id,name,sobjecttype,developername from recordtype where (sobjecttype=:'ConsumerEducation__c' and developername=:'p_class') 
                                       or (sobjecttype=:'event' and developername=:'PClass')
                                       or (sobjecttype=:'callplan__c' and developername=:'Pclass')
                                       or (sobjecttype=:'event' and developername=:'PocketSessionOrSaloon')
                                       or (sobjecttype=:'event' and developername=:'CallPlan')
                                       or (sobjecttype=:'ConsumerEducation__c' and developername=:'local')
                                       or (sobjecttype=:'ConsumerEducation__c' and developername=:'national')
                                       or (sobjecttype=:'event' and developername=:'nationalCS')
                                        ];
                    
   string name;
   recordtype rt;  //=[select id,name from recordtype where sobjecttype=:'ConsumerEducation__c' and name=:'妈妈班'];
   recordtype eventrt;  //=[select id from recordtype where sobjecttype=:'event' and name=:'妈妈班'];
   recordtype cppsrt;
   recordtype epsrt;
   recordtype ecprt;
   recordtype local;
   recordtype national;
   recordtype enart;
   
   for(recordtype a:allrt){
       if(a.sobjecttype=='ConsumerEducation__c' && a.developername=='p_class'){
           rt=a;
       }
       if(a.sobjecttype=='event' && a.developername=='PClass'){
           eventrt=a;
       }
       if(a.sobjecttype=='event' && a.developername=='nationalCS'){
           enart=a;
       }
       if(a.sobjecttype=='callplan__c' && a.developername=='Pclass'){
           cppsrt=a;
       }
       if(a.sobjecttype=='event' && a.developername=='PocketSessionOrSaloon'){
           epsrt=a;
       }
       if(a.sobjecttype=='event' && a.developername=='CallPlan'){
           ecprt=a;
       }
       if(a.sobjecttype=='ConsumerEducation__c' && a.developername=='local'){
           local=a;
       }
       if(a.sobjecttype=='ConsumerEducation__c' && a.developername=='national'){
           national=a;
       }
       
   }
   
  if(System.Trigger.Isinsert||System.Trigger.Isupdate){
      for(ConsumerEducation__c c:trigger.new){
    newdate = datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(integer i=1;i<=30;i++){
        cpdate.add(newdate);
        newdate=newdate.addMinutes(30);
    }
   }
   
    if(system.trigger.isupdate){
    for(ConsumerEducation__c c:trigger.old){
    olddate = datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(integer i=1;i<=30;i++){
        cpdate.add(olddate);
        olddate=olddate.addMinutes(30);
    }
   }
   }
 string rtype;  
 id rid;
for(ConsumerEducation__c c:trigger.new){
  if(system.trigger.isinsert){
                rtype=null;
                if(c.recordtypeid==local.id){
                    rtype=local.name;
                }
                if(c.recordtypeid==rt.id){
                    rtype=rt.name;
                }
                if(c.recordtypeid==national.id){
                    rtype=national.name;
                }
                
                if(c.recordtypeid==rt.id){
                      rid=eventrt.id;
                 }else{
                      rid=enart.id;
                 }
                 
                 if(c.time__c=='下午'){
                     Event e = new Event(Subject=rtype, 
                                    WhatId=c.id,
                                    recordtypeid=rid,
                                    StartDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 6, 0, 0),
                                    EndDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 9, 0, 0),
                                    IsReminderSet = false,
                                    hospitalname__c=c.hospital__r.name,
                                    eventdate__c=c.date__c
                                    );
                 eventins.add(e);
                 }else{
                     Event e = new Event(Subject=rtype, 
                                    WhatId=c.id,
                                    recordtypeid=rid,
                                    StartDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 1, 0, 0),
                                    EndDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 4, 0, 0),
                                    IsReminderSet = false,
                                    hospitalname__c=c.hospital__r.name,
                                    eventdate__c=c.date__c
                                    );
                 eventins.add(e);
                 }
                
       }
}
if(eventins.size()>0){
    insert eventins;
}

list<event> all=[select id,StartDateTime,whatid,recordtypeid from event e where e.ownerid=:userinfo.getuserid() and e.startdatetime in :cpdate order by hospitalname__c];
if(system.trigger.isupdate){
for(ConsumerEducation__c c:trigger.new){
if(c.recordtypeid!=rt.id){
    for(event a:all){
        if(a.whatid==c.id){ 
            if(c.time__c=='上午'){
                a.startdatetime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 1, 0, 0);
            }else{
                 a.startdatetime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 6, 0, 0);
            }
        }
    }
    }
}
update all;
}
if((system.trigger.isupdate&&b)||system.trigger.isinsert){
//string soql='select id,StartDateTime,whatid from event e where e.ownerid=userinfo.getuserid() and e.startdatetime in cpdate order by (select name from callplan__c where id=e.whatid)';//查询出所有当日的event
//list<event> all=Database.query(soql);
list<event> pocketl=new list<event>();
list<event> pclassl=new list<event>();
list<event> callplanl=new list<event>();
list<event> updatel=new list<event>();
datetime datime;


if(system.trigger.isupdate){
for(ConsumerEducation__c c:trigger.new){
if(c.recordtypeid==rt.id){
    for(event a:all){
        if(a.whatid==c.id){ 
                a.startdatetime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
        }
    }
    }
}
update all;
}

for(ConsumerEducation__c c:trigger.new){
if(updatel.size()>0){
    if( updatel[0].startdatetime.date() != c.date__c){
        update updatel;
    }
    updatel.clear();
}
pocketl.clear();
pclassl.clear();
callplanl.clear();
    datime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(event e:all){
      if(e.StartDateTime.date()==c.date__c){
        if(e.recordtypeid==epsrt.id){
            pocketl.add(e);
        }
        if(e.recordtypeid==eventrt.id){
            pclassl.add(e);
        }
        if(e.recordtypeid==ecprt.id){
            callplanl.add(e);
        }
      }
    }
    
    for(event p:pocketl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    for(event p:pclassl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    for(event p:callplanl){
        p.StartDateTime=datime;
        datime=datime.addMinutes(30);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    
}
if(system.trigger.isupdate){
for(ConsumerEducation__c c:trigger.old){
pocketl.clear();
pclassl.clear();
callplanl.clear();
    datime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(event e:all){
      if(e.StartDateTime.date()==c.date__c&&e.whatid!=c.id){
         if(e.recordtypeid==epsrt.id){
            pocketl.add(e);
        }
        if(e.recordtypeid==eventrt.id){
            pclassl.add(e);
        }
        if(e.recordtypeid==ecprt.id){
            callplanl.add(e);
        }
      }
    }
    
    for(event p:pocketl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    for(event p:pclassl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    for(event p:callplanl){
        p.StartDateTime=datime;
        datime=datime.addMinutes(30);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    
}
}
update updatel;
}
   
   
   
   /*
       if(idl.size()>0){
           idl.clear();
       }
       for(ConsumerEducation__c ce:trigger.new){
           idl.add(ce.id);
       }
      eventl=[select Subject,WhatId,StartDateTime,EndDateTime from Event where whatId in:idl];
      if(eventl.size()>0){
               for(ConsumerEducation__c ce:trigger.new){
                  if(ce.RecordTypeId==rt.id){
                      time starttime = time.newInstance(9,0,0,0);
                      time endtime = time.newInstance(9,0,0,0);
                  if(ce.time__c == '上午'){
                      starttime = time.newInstance(9,0,0,0);
                      endtime=time.newInstance(12,0,0,0);
                  }
                  else if (ce.time__c == '下午'){
                      starttime = time.newInstance(14,0,0,0);
                      endtime = time.newInstance(17,0,0,0);
                  }
                 Datetime startdate=datetime.newinstance(ce.date__c,starttime);
                 Datetime enddate=datetime.newinstance(ce.date__c,endtime);
                 
                for(event e:eventl){
                   if(e.whatid==ce.id){
                   e.StartDateTime=startdate;
                   e.EndDateTime=enddate;
                   e.IsReminderSet=false;
                   eventupd.add(e);
                   }
                   }
                  }
          }
      }else if(eventl.size()==0){
      for(ConsumerEducation__c ce:trigger.new){
                  if(ce.RecordTypeId==rt.id){
                      time starttime = time.newInstance(9,0,0,0);
                      time endtime = time.newInstance(9,0,0,0);
                  if(ce.time__c == '上午'){
                      starttime = time.newInstance(9,0,0,0);
                      endtime=time.newInstance(12,0,0,0);
                  }
                  else if (ce.time__c == '下午'){
                      starttime = time.newInstance(14,0,0,0);
                      endtime = time.newInstance(17,0,0,0);
                  }
                 Datetime startdate=datetime.newinstance(ce.date__c,starttime);
                 Datetime enddate=datetime.newinstance(ce.date__c,endtime);
                 
                  Event e=new Event(Subject=rt.name,
                                RecordTypeId=eventrt.id,
                                WhatId=ce.Id,
                                StartDateTime=startdate,
                                EndDateTime=enddate,
                                IsReminderSet = false
                                 );
                    eventins.add(e);
                  }
          }
      }
      update eventupd;
      insert eventins;
      */
      
      
      
   List<consumereducation__c> psl=new list<consumereducation__c>();
            list<callplan__c> cpins=new list<callplan__c>();
            list<callplan__c> cpupd=new list<callplan__c>();
            list<id> psmark=new list<id>();
            list<monthlycallplan__c> mcpins=new list<monthlycallplan__c>();
             list<datetime> sdt=new list<datetime>();
            list<MonthlyCallPlan__c> mcpl=new list<MonthlyCallPlan__c>();
            string month;
            string year;
            integer currentdate;
            time t;
            datetime dt;
            boolean mark=true;
            string dtime;
            
            psl=[select id,date__c,time__c,name from consumereducation__c where id in:trigger.new and recordtypeid=:rt.id];
            mcpl=[select id,PlanYear__c,PlanMonth__c from monthlycallplan__c where ownerid=:userinfo.getuserid()];
            string plantype;
            
      if(system.trigger.isinsert && trigger.new[0].recordtypeid==rt.id && trigger.new[0].date__c>date.today()){
           
            for(consumereducation__c ps:trigger.new){
                month=ps.date__c.month()+'月';
                year=ps.date__c.year()+'';
                currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());
                
         //       if(currentdate>0){
                    plantype='计划内';
         /*       }else{
                    plantype='计划外';
                }*/

                if(ps.time__c == '上午'){
                        t= time.newInstance(9,0,0,0);
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(14,0,0,0);
                }
                dt=datetime.newinstance(ps.date__c,t);

                for(monthlycallplan__c mcp:mcpl){
                    if(year==mcp.planyear__c && month==mcp.planmonth__c){
                        callplan__c cp=new callplan__c(name='妈妈班:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
                       
                        //Lasts__c=1,
                        CallWorkingtype__c='妈妈班',Monthly_Call_Plan__c=mcp.id,CallMessage__c=ps.messaging__c,activityid__c=ps.id);
                        cpins.add(cp);
                        mark=false;
                    }
                }
                if(mark){
                    monthlycallplan__c newmcp=new monthlycallplan__c(PlanMonth__c=month,planyear__c=year,name=userinfo.getlastname()+userinfo.getfirstname() + year + '年' + month + '拜访计划');
                    insert newmcp;
                    callplan__c cp=new callplan__c(name='妈妈班:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
           
                        //Lasts__c=1,
                        CallWorkingtype__c='妈妈班',Monthly_Call_Plan__c=newmcp.id,CallMessage__c=ps.messaging__c,activityid__c=ps.id);
                        cpins.add(cp);
                }
              
            }
       }else if(system.trigger.isupdate && trigger.new[0].recordtypeid==rt.id && trigger.old[0].date__c>date.today()){
             for(consumereducation__c ps:trigger.old){
                month=ps.date__c.month()+'月';
                year=ps.date__c.year()+'';
                currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());
                
                if(currentdate>0){
                    plantype='计划内';
                }else{
                    plantype='计划外';
                }

                if(ps.time__c == '上午'){
                        t= time.newInstance(17,0,0,0);
                        dtime='AM(9am-12am)';
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(22,0,0,0);
                        dtime='PM(2pm-5pm)';
                }
                dt=null;
                dt=datetime.newinstance(ps.date__c,t);
                name='妈妈班:'+trigger.old[0].name;
            }
            Set <String> setname= new Set<String>();
            list<callplan__c> cpl=new list<callplan__c>();
            list<callplan__c> ucpl=new list<callplan__c>();
            ucpl=[select id from callplan__c where activityid__c=:trigger.old[0].id and IsDeleted =: false];//name=:name and CallPlanDate__c=:trigger.old[0].date__c and ownerid__c=:string.valueof(trigger.old[0].ownerid).substring(0,15)
            for(consumereducation__c ps:trigger.new){
                month=ps.date__c.month()+'月';
                year=ps.date__c.year()+'';
                currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());
                
          //      if(currentdate>0){
                    plantype='计划内';
            /*    }else{
                    plantype='计划外';
                }*/

                if(ps.time__c == '上午'){
                        t= time.newInstance(9,0,0,0);
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(14,0,0,0);
                }
                dt=datetime.newinstance(ps.date__c,t);
//by scao
                for(callplan__c cp:ucpl){
                   cp.delete_mark__c=true;
                }            
                


/*by siheng              
            for(callplan__c cpl1:ucpl){
                  delete cpl1;
            }
*/            
                for(monthlycallplan__c mcp:mcpl){
                    if(year==mcp.planyear__c && month==mcp.planmonth__c){
                        callplan__c cp=new callplan__c(name='妈妈班:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
                        //Lasts__c=1,
                                              
                        CallWorkingtype__c='妈妈班',Monthly_Call_Plan__c=mcp.id,CallMessage__c=ps.Messaging__c,activityid__c=ps.id);
                        cpins.add(cp);
                        mark=false;
                    }
                }
                if(mark){
                    monthlycallplan__c newmcp=new monthlycallplan__c(PlanMonth__c=month,planyear__c=year,name=userinfo.getlastname()+userinfo.getfirstname() + year + '年' + month + '拜访计划');
                    insert newmcp;
                    callplan__c cp=new callplan__c(name='妈妈班:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
                        //Lasts__c=1,
                                                         
                        CallWorkingtype__c='妈妈班',Monthly_Call_Plan__c=newmcp.id,CallMessage__c=ps.Messaging__c,activityid__c=ps.id);
                        cpins.add(cp);
                }
          }
            update ucpl;
            delete ucpl;           
      }
      insert cpins;

      
/*      for(ConsumerEducation__c ce:trigger.new){
      if(ce.RecordTypeId==rt.id){
          time starttime = time.newInstance(9,0,0,0);
          time endtime = time.newInstance(9,0,0,0);
      if(ce.time__c == '上午'){
          starttime = time.newInstance(9,0,0,0);
          endtime=time.newInstance(12,0,0,0);
      }
      else if (ce.time__c == '下午'){
          starttime = time.newInstance(14,0,0,0);
          endtime = time.newInstance(17,0,0,0);
      }
     Datetime startdate=datetime.newinstance(ce.date__c,starttime);
     Datetime enddate=datetime.newinstance(ce.date__c,endtime);
 
        if(System.Trigger.Isinsert){
 
              Event e=new Event(Subject=rt.name,
                                RecordTypeId=eventrt.id,
                                WhatId=ce.Id,
                                StartDateTime=startdate,
                                EndDateTime=enddate,
                                IsReminderSet = false, 
                                ReminderDateTime = startdate.addMinutes(-15)
                                 );   insert e; }                
                                 
                                 
        else if(System.trigger.isupdate){
              eventl=[select Subject,WhatId,StartDateTime,EndDateTime from Event where whatId=:ce.id];
              if(eventl.size()>0){
              Event e=eventl[0];
              e.StartDateTime=startdate;
              e.EndDateTime=enddate;
              e.IsReminderSet=false;
              e.ReminderDateTime=startdate.addminutes(-15);
              
              update e;
             
              }
             }
        
             }
            } 
            }
        */
      
   
   
   
   }else if(System.Trigger.Isdelete){
    if(idl.size()>0){
        idl.clear();
    }
    for(consumereducation__c ce:trigger.old){
        idl.add(ce.id);
    }
     
     eventl=[select Subject,WhatId,StartDateTime,EndDateTime from Event where whatId in:idl];
     if(eventl.size()>0){
         delete eventl;
     }
     
   for(consumereducation__c c:trigger.old){
    newdate = datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(integer i=1;i<=30;i++){
        cpdate.add(newdate);
        newdate=newdate.addMinutes(30);
    }
   }
     
    
//string soql='select id,StartDateTime,whatid from event e where e.ownerid=userinfo.getuserid() and e.startdatetime in cpdate order by (select name from callplan__c where id=e.whatid)';//查询出所有当日的event
//list<event> all=Database.query(soql);
list<event> all=[select id,StartDateTime,whatid,recordtypeid from event e where e.ownerid=:userinfo.getuserid() and e.startdatetime in :cpdate order by hospitalname__c];
list<event> pocketl=new list<event>();
list<event> pclassl=new list<event>();
list<event> callplanl=new list<event>();
list<event> updatel=new list<event>();
datetime datime;
for(ConsumerEducation__c c:trigger.old){
if(updatel.size()>0){
    if( updatel[0].startdatetime.date() != c.date__c){
        update updatel;
    }
    updatel.clear();
}
pocketl.clear();
pclassl.clear();
callplanl.clear();
    datime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(event e:all){
      if(e.StartDateTime.date()==c.date__c){
        if(e.recordtypeid==epsrt.id){
            pocketl.add(e);
        }
        if(e.recordtypeid==eventrt.id){
            pclassl.add(e);
        }
        if(e.recordtypeid==ecprt.id){
            callplanl.add(e);
        }
      }
    }
    
    for(event p:pocketl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    for(event p:pclassl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    for(event p:callplanl){
        p.StartDateTime=datime;
        datime=datime.addMinutes(30);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    // remove dupes
    for(Integer i = 0; i < updatel.size()-1; i++)
        for(Integer j = 1; j < updatel.size(); j++)
            if(updatel.get(i).id == updatel.get(j).id)
                updatel.remove(j);
    
    update updatel;
    updatel.clear();    
}


    
     
                string plantype;
                time t;
                string dtime;
       for(consumereducation__c ps:trigger.old){
                string month=ps.date__c.month()+'月';
                string year=ps.date__c.year()+'';
                integer currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());

                
                if(currentdate>0){
                    plantype='计划内';
                }else{
                    plantype='计划外';
                }

                if(ps.time__c == '上午'){
                        t= time.newInstance(17,0,0,0);
                        dtime='AM(9am-12am)';
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(22,0,0,0);
                        dtime='PM(2pm-5pm)';
                }
               name='妈妈班:'+trigger.old[0].name;
               datetime dt=datetime.newinstance(ps.date__c,t);
            }
            list<callplan__c> cpl=new list<callplan__c>();
            list<callplan__c> ucpl=new list<callplan__c>();
            List<String> idstr = new List<String>();
            
            for(consumereducation__c cs : trigger.old)
                idstr.add(cs.id);
            
            ucpl=[select id from callplan__c where activityid__c in : idstr and IsDeleted =: false];//createddate=:trigger.old[0].createddate and name=:name and CallPlanDate__c=:trigger.old[0].date__c and ownerid__c=:userinfo.getuserid().substring(0,15)
            if(ucpl.size()>0){
                for(callplan__c cp:ucpl){
                   cp.delete_mark__c=true;
                }            
                
                update ucpl;
                delete ucpl;
            }
            
            
   }

}